package fr.webviewer.activity;

import java.util.Set;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ToggleButton;
import fr.webviewer.data.RoadEntry;
import fr.webviewer.data.RoadEntryPool;
import fr.webviewer.transformation.ScreenMapping;
import fr.webviewer.transformation.WebViewZoom;

/**
 * Activity which shows the traffic view considering the user's preferencies
 * @author Anthony
 *
 */
public class TrafficViewActivity extends Activity {

	private WebView webview;

	private Point scroll;

	private WebViewZoom zoom;
	
	private Set<RoadEntry> roadEntrySet;

	private Rect screenSize;

	private Rect image;

	private Rect imageAreaToShow;

	private boolean comeFromPause;

	private SharedPreferences preferences;

	private ToggleButton resetButton;
	
	private String url = "http://www.bison-fute.equipement.gouv.fr/astec_acai/internet/ie1_bordeaux.html";

	private final static int IMAGE_WIDTH = 580;
	
	private final static int IMAGE_HEIGHT = 472;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		comeFromPause = false;
		setContentView(R.layout.main);
		preferences = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		roadEntrySet = new TreeSet<RoadEntry>();
		webview = (WebView) findViewById(R.id.WebView01);
		Display display = getWindowManager().getDefaultDisplay();
		screenSize = new Rect(0, 0, display.getWidth(), display.getHeight());
		image = new Rect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
				
		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setBuiltInZoomControls(true);
		
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				refreshView();
			}
		});
		
		resetButton = (ToggleButton) findViewById(R.id.ResetButton);
		boolean isFullScreen = preferences.getBoolean("fullScreen", true);
		resetButton.setChecked(isFullScreen);
		resetButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Editor editor = preferences.edit();
				editor.putBoolean("fullScreen", resetButton.isChecked());
				editor.commit();
				refreshView();
			}

		});
		
		Button roadButton = (Button) findViewById(R.id.RoadButton);
		roadButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent settingsActivity = new Intent(getBaseContext(),
						PreferenceActivity.class);
				Bundle bundle = new Bundle();
				bundle.putBoolean("Time", false);
				settingsActivity.putExtras(bundle);
				startActivity(settingsActivity);				
			}
		});
		Button timeButton = (Button) findViewById(R.id.TimeButton);
		timeButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent settingsActivity = new Intent(getBaseContext(),
						PreferenceActivity.class);
				Bundle bundle = new Bundle();
				bundle.putBoolean("Time", true);
				settingsActivity.putExtras(bundle);
				startActivity(settingsActivity);				
			}
		});
		webview.loadUrl(url);
	}

	private void resetData(){
		zoom = ScreenMapping.getZoom(screenSize, image,
				image, webview.getScale());
		scroll = ScreenMapping.getScroll(image, zoom);
	}

	private void displayView(){
		if(zoom.getZoomStep() > 0){
			//If a zoomIn is needed
			for(int i = 0; i < zoom.getZoomStep(); i++){
				webview.zoomIn();
			}					
		} else if(zoom.getZoomStep() < 0) {
			//If a zoomOut is needed
			for(int i = 0; i > zoom.getZoomStep(); i--){
				webview.zoomOut();
			}					
		}
		// When the zoom is done, scroll the view
		webview.scrollTo(scroll.x, scroll.y);				
	}
	
	private Point getIntermediateScroll(Point current, Point target, float zoom){
		Point result = new Point();
		result.x = Float.valueOf((current.x / 2 + (target.x / 2)) * zoom).intValue();
		result.y = Float.valueOf((current.y / 2 + (target.y / 2)) * zoom).intValue();
		return result;
	}
	
	@Override
	public void onResume() {
		if (comeFromPause) {
			webview.loadUrl(url);
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		comeFromPause = true;
		super.onPause();
	}

	private void refreshView(){
		if(resetButton.isChecked()){
			resetData();
			displayView();
		} else {
			getDataFromPrefs();
			displayView();
		}
	}
	
	private void getDataFromPrefs() {
		roadEntrySet.clear();
		roadEntrySet.addAll(RoadEntryPool.getInstance().getRoadBetween(
				preferences.getString(PreferenceActivity.KEYS[0] + PreferenceActivity.ROAD_KEY, "1"),
				preferences.getString(PreferenceActivity.KEYS[1] + PreferenceActivity.ROAD_KEY, "1")));
		roadEntrySet.addAll(RoadEntryPool.getInstance().getRoadBetween(
				preferences.getString(PreferenceActivity.KEYS[2] + PreferenceActivity.ROAD_KEY, "1"),
				preferences.getString(PreferenceActivity.KEYS[3] + PreferenceActivity.ROAD_KEY, "1")));
		imageAreaToShow = ScreenMapping.getImageAreaToShow(roadEntrySet);
		zoom = ScreenMapping.getZoom(screenSize, image,
				imageAreaToShow, webview.getScale());
		scroll = ScreenMapping.getScroll(imageAreaToShow, zoom);
	}

}
